import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
#股票综合评估
# ------------ 熵权法函数 ------------
def entropy_weight(data):
    """计算指标的熵权"""
    data = pd.DataFrame(data).replace(0, 1e-9)
    data_norm = data / data.sum(axis=0)
    entropy = -np.sum(data_norm * np.log(data_norm), axis=0) / np.log(len(data))
    weight = (1 - entropy) / np.sum(1 - entropy)
    return weight.values

# ------------ 手动TOPSIS计算 ------------
def topsis(data, weights, impacts):
    # 标准化
    norm_data = data / np.linalg.norm(data, axis=0)
    # 理想解与负理想解
    ideal_best = np.max(norm_data * impacts, axis=0)
    ideal_worst = np.min(norm_data * impacts, axis=0)
    # 距离计算
    d_best = np.sqrt(np.sum((norm_data - ideal_best)**2 * weights, axis=1))
    d_worst = np.sqrt(np.sum((norm_data - ideal_worst)**2 * weights, axis=1))
    # 综合评分
    score = d_worst / (d_best + d_worst)
    return score

# ------------ 主流程 ------------
# 1. 加载数据
df = pd.read_excel(r"F:\上市公司综合数据\LHTZ评估数据.xlsx")
df = df[df['ROE'] > 0]  # 剔除异常值

# 2. 指标选择与处理
criteria = ['ROE', '净利润(亿元)', '4.资产周转率', '资产负债率']
data = df[criteria].copy()
data['资产负债率'] = 1 - data['资产负债率']  # 负向指标正向化

# 3. 数据标准化
scaler = MinMaxScaler()
data_scaled = scaler.fit_transform(data)

# 4. 熵权法计算权重
weights = entropy_weight(data_scaled)

# 5. 手动TOPSIS计算（所有指标为正向）
impacts = np.array([1, 1, 1, 1])  # 正向指标
df['综合评分'] = topsis(data_scaled, weights, impacts)
df['排名'] = df['综合评分'].rank(ascending=False)

# 6. 输出结果
print(df[['股票代码', '公司名称', 'ROE', '净利润(亿元)', '综合评分', '排名']]
      .sort_values('排名').head(37))








